/**
 * 
 */
package br.edu.ufcg.embedded.util;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * @author daniel
 *
 */
public class MultiFileGenerator
{
	private FileManager fileManager;
	private int lineCount;
	private int maxLines;
	
	private String filePath;
	private String fileName;
	private String extension;
	
	private String currentFile;
	
	private boolean create;
	
	public MultiFileGenerator(String filePath, String fileName, String extension, int maxLines)
	{
		this.filePath = filePath;
		this.fileName = fileName;
		this.extension = extension;
		
		this.currentFile = null;
		this.create = true;
		
		this.fileManager = new FileManager();
		this.maxLines = maxLines;
		this.lineCount = 0;
	}
	
	public void close()
	{
		if (isFileOpen())
			fileManager.close();
		
		rename();
	}
	
	private void rename()
	{
		File oldFile = new File(currentFile);
		oldFile.renameTo(new File(currentFile + extension));
	}
		
	public void write(String text)
	{
		if (create)
			createFile();
			
		fileManager.write(text);
		lineCount++;
		
		if (lineCount == maxLines)
		{
			fileManager.close();
			rename();
			create = true;
		}
	}
	
	private void createFile()
	{
		lineCount = 0;
		
		StringBuffer sb = new StringBuffer();
		sb.append(filePath);
		sb.append(fileName);
		sb.append("_");
		sb.append(new Timestamp(System.currentTimeMillis()));
		
		try {
			currentFile = sb.toString();
			fileManager.openOrCreateFile(currentFile);
			create = false;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private boolean isFileOpen()
	{
		return !create;
	}
}
